<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="header-left" @click="goBack" :style="{ marginTop: safeTop + 'px' }">
				<image src="/static/base/back.svg" class="back-icon" mode="aspectFit" />
			</view>
			<view class="header-title" :style="{ marginTop: safeTop + 'px' }">个人主页</view>
			<view class="header-right">
			</view>
		</view>

		<scroll-view scroll-y class="content">
			<view :style="{ height: contentTop + 'px' }"></view>

			<!-- 设计师信息 -->
			<view class="designer-info-section">
				<view class="user-title">
					<image :src="designer.avatar || '/static/images/f.png'" class="designer-avatar" mode="aspectFill" />

					<view class="designer-name-box">
						<text class="designer-name">{{ designer.nickname || '未设置昵称' }}</text>
						<image v-if="designer.identity != 2 & designer.work_level > 0" class="mvp-img"
						 :src="'/static/base/user-center/level/'+levelImg">
						</image>
						<text style="margin-left:20rpx" v-if="designer.identity != 2 & designer.work_level == 0">普通创作者</text>
						<view class="designer-tag" v-if="designer.identity == 2">
							<image class="designer-icon" src="/static/base/index/write.png"></image>
							设计师
						</view>
					</view>
				</view>
				<text class="designer-description">{{ designer.signature || '暂无个性签名' }}</text>
				
				<!-- 统计数据 -->
				<view class="stats-section">
					<view class="date-box">
						<view class="stat-item">
							<text class="stat-number">{{ designer.work_count || 0 }}</text>
							<text class="stat-label">作品</text>
						</view>
						<view class="stat-item" @click="gotoFollowList">
							<text class="stat-number">{{ designer.follow_count || 0 }}</text>
							<text class="stat-label">关注</text>
						</view>
						<view class="stat-item" @click="gotoFansList">
							<text class="stat-number">{{ designer.fans_count || 0 }}</text>
							<text class="stat-label">粉丝</text>
						</view>
						<view class="stat-item">
							<text class="stat-number">{{ designer.work_like_count || 0 }}</text>
							<text class="stat-label">获赞</text>
						</view>
					</view>

					<view>
						<!-- 操作按钮 -->
						<view class="action-buttons">
							<view class="follow-btn" @click="toggleFollow" v-if="currentUId!=designer.uid">
								<text class="follow-text">{{ designer.is_follow ? '已关注' : '关注' }}</text>
							</view>

							<!-- <view class="message-btn" @click="sendMessage">
								<text class="message-text">私信</text>
							</view> -->
						</view>
					</view>
				</view>
			</view>

			<!-- 标签栏 -->
			<view class="tabs">
				<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
					:class="{ active: currentTab === index }" @click="switchTab(index)">
					<text class="tab-text">{{ tab.name }}</text>
					<view v-if="currentTab === index" class="tab-underline"></view>
				</view>
			</view>

			<!-- 内容区域 -->
			<view class="tab-content">
				<!-- 代表作品 -->
				<view v-if="currentTab === 0 && tabs.length > 1" class="works-grid">
					<view v-if="representativeWorks.length === 0" class="empty-tip">还没有作品哦~</view>
					<view v-else v-for="(work, index) in representativeWorks" :key="index" class="work-item"
						@click="goToWorkDetail(work.id)">
						<image :src="work.image" class="work-image" mode="aspectFill" />
						<view class="work-info">
							<!-- 设计稿不显示标题 -->
							<!-- <text class="work-title">{{ work.title }}</text> -->
							<view class="work-meta">
								<image :src="designer.avatar || '/static/images/f.png'" class="author-icon"
									mode="aspectFit" />
								<text class="author-name">{{ work.author }}</text>
								<!-- <view class="like-box" @click.stop="handleRepresentaLike(work.id)">
									<image v-if="work.islike" src="/static/base/index/good-active.png" class="like-icon"
										mode="aspectFit" />
									<image v-else src="/static/base/index/good.png" class="like-icon"
										mode="aspectFit" />
									<text class="like-count">{{ work.likes }}</text>
								</view> -->
								<view class="like-box">
									<image v-if="work.islike" src="/static/base/index/good-active.png" class="like-icon"
										mode="aspectFit" />
									<image v-else src="/static/base/index/good.png" class="like-icon"
										mode="aspectFit" />
									<text class="like-count">{{ work.likes }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 设计作品 -->
				<view v-if="currentTab === 1 && tabs.length > 1" class="works-grid">
					<view v-if="designWorks.length === 0" class="empty-tip">还没有作品哦~</view>
					<view v-else v-for="(work, index) in designWorks" :key="index" class="work-item"
						@click="goToWorkDetail(work.id)">
						<image :src="work.image" class="work-image" mode="aspectFill" />
						<view class="work-info">
							<!-- 设计稿不显示标题 -->
							<!-- <text class="work-title">{{ work.title }}</text> -->
							<view class="work-meta">
								<image :src="work.avatar" class="author-icon" mode="aspectFit" />
								<text class="author-name">{{ work.author }}</text>
								<view class="like-box" @click.stop="handleDesignLike(work.id)">
									<image v-if="work.islike" src="/static/base/index/good-active.png" class="like-icon"
										mode="aspectFit" />
									<image v-else src="/static/base/index/good.png" class="like-icon"
										mode="aspectFit" />
									<text class="like-count">{{ work.likes }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 我的创作 -->
				<view v-if="currentTab === 2 || tabs.length==1" class="works-grid">
					<view v-if="works.length === 0" class="empty-tip">还没有作品哦~</view>
					<view v-else v-for="(work, index) in works" :key="index" class="work-item"
						@click="goToDetail(work.id)">
						<image :src="work.image" class="work-image" mode="aspectFill" />
						<view class="work-info">
							<text class="work-title">{{ work.title }}</text>
							<view class="work-meta">
								<image :src="work.avatar" class="author-icon" mode="aspectFit" />
								<text class="author-name">{{ work.author }}</text>
								<view class="like-box" @click.stop="handleDesignLike(work.id)">
									<image v-if="work.islike" src="/static/base/index/good-active.png" class="like-icon"
										mode="aspectFit" />
									<image v-else src="/static/base/index/good.png" class="like-icon"
										mode="aspectFit" />
									<text class="like-count">{{ work.likes }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>

			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		getUserInfo,
		getUserWorkList,
		getDraftList
	} from '@/api/base/designer.js'

	import Cache from '@/utils/cache';
	import {
		UID
	} from '@/config/cache';
	
	import {
		followUser,
		cancelFollowUser
	} from '@/api/base/index.js'

	// 默认作品图片（请确保该路径图片存在）
	const DEFAULT_WORK_IMAGE = '/static/base/empty.png'

	export default {
		data() {
			return {
				currentUId: '',
				safeTop: 0,
				contentTop: 0,
				designerId: '',
				currentTab: 0,
				tabs: [{
						name: '代表作品'
					},
					{
						name: '设计作品'
					},
					{
						name: '我的创作'
					}
				],
				designer: {
					uid: null,
					nickname: '',
					avatar: '',
					signature: '',
					identity: '',
					work_count: 0,
					follow_count: 0,
					fans_count: 0,
					work_like_count: 0,
					is_follow: false
				},
				representativeWorks: [], // type=2
				designWorks: [] ,// type=1
				works: [],
			}
		},
		computed: {
			levelName() {
				const map = ['普通创作者', '青铜创作者', '白银创作者', '黄金创作者', '钻石创作者', '王者创作者'];
				return map[this.designer.work_level];
			},
			levelImg() {
				const map = ['', '1.png', '2.png', '3.png', '4.png', '5.png'];
				return map[this.designer.work_level];
			}
		},
		onShow() {
			this.currentUId = Cache.get(UID);
			this.loadDesignerInfo();
		},
		onLoad(options) {
			const {
				barTop
			} = this.$util.getWXStatusHeight();
			this.safeTop = barTop;
			this.contentTop = barTop + 44;

			this.designerId = options.id || '1';

			// this.loadDesignerInfo();
			// this.loadWorkList(2); // 默认加载代表作品（type=2）
		},
		methods: {
			async loadDesignerInfo() {
				try {
					const res = await getUserInfo(this.designerId);
					if (res.status === 200 && res.data) {
						this.designer = res.data;
						console.log(this.designer)
						// this.designer.work_level = 2
						if(this.designer.identity == 2){
							//设计师
							this.loadWorkList(2); // 默认加载代表作品（type=2）
						}else{
							//创作者主页
							this.tabs = [{
								name: '我的创作'
							}]
							this.loadWorks()
						}
						
					} else {
						uni.showToast({
							title: res.msg || '获取用户信息失败',
							icon: 'none'
						});
					}
				} catch (err) {
					console.error('获取用户信息失败', err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				}
			},

			async loadWorkList(type) {
				try {
					const res = await getDraftList(this.designerId, type);
					if (res.status === 200 && Array.isArray(res.data.list)) {
						const works = res.data.list.map(item => {
							let firstImage = DEFAULT_WORK_IMAGE;
							// 处理 images 字段：可能为 null、[]、或字符串（兼容）
							if (Array.isArray(item.images) && item.images.length > 0 && item.images[0]) {
								firstImage = item.images[0];
							} else if (typeof item.images === 'string' && item.images.trim()) {
								firstImage = item.images;
							}

							return {
								id: item.id,
								title: item.title || '无标题',
								image: firstImage,
								avatar: item.avatar || this.designer.avatar || '/static/images/f.png',
								author: item.nickname || this.designer.nickname || '匿名',
								likes: item.likeNum || 0,
								islike: false // 实际点赞状态需另接口，此处仅前端模拟
							};

						});

						if (type === 2) {
							this.representativeWorks = works;
						} else if (type === 1) {
							this.designWorks = works;
						}
					} else {
						uni.showToast({
							title: res.msg || '获取作品失败',
							icon: 'none'
						});
						if (type === 2) this.representativeWorks = [];
						else this.designWorks = [];
					}
				} catch (err) {
					console.error('获取作品列表失败', err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
					if (type === 2) this.representativeWorks = [];
					else this.designWorks = [];
				}
			},

			async loadWorks() {
				try {
					const res = await getUserWorkList(this.designerId, 1);
					if (res.status === 200 && Array.isArray(res.data.list)) {
						const works = res.data.list.map(item => {
							let firstImage = DEFAULT_WORK_IMAGE;
							// 处理 images 字段：可能为 null、[]、或字符串（兼容）
							if (Array.isArray(item.images) && item.images.length > 0 && item.images[0]) {
								firstImage = item.images[0];
							} else if (typeof item.images === 'string' && item.images.trim()) {
								firstImage = item.images;
							}

							return {
								id: item.id,
								title: item.title || '无标题',
								image: firstImage,
								avatar: item.avatar || this.designer.avatar || '/static/images/f.png',
								author: item.nickname || this.designer.nickname || '匿名',
								likes: item.likeNum || 0,
								islike: false // 实际点赞状态需另接口，此处仅前端模拟
							};

						});
						this.works = works;
					} else {
						uni.showToast({
							title: res.msg || '获取作品失败',
							icon: 'none'
						});
						this.works = [];
					}
				} catch (err) {
					console.error('获取作品列表失败', err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
					this.works = [];
				}
			},

			gotoFollowList() {
				uni.navigateTo({
					url: `/pages/sub_base/follow-list/index?uid=${this.designerId}`
				})
			},
			gotoFansList() {
				uni.navigateTo({
					url: `/pages/sub_base/fans-list/index?uid=${this.designerId}`
				})
			},
			switchTab(index) {
				if (this.currentTab === index) return;
				this.currentTab = index;
				if(index == 2){
					this.loadWorks()
					return
				}
				const type = index === 0 ? 2 : 1; // 0:代表作(type=2), 1:设计作品(type=1)
				this.loadWorkList(type);
			},

			async toggleFollow() {
				const newFollowState = !this.designer.is_follow;
				try {
					if (newFollowState) {
						await followUser(this.designerId);
					} else {
						await cancelFollowUser(this.designerId);
					}
					this.designer.is_follow = newFollowState;
					this.designer.fans_count = newFollowState ?
						this.designer.fans_count + 1 :
						Math.max(0, this.designer.fans_count - 1);

					uni.showToast({
						title: newFollowState ? '已关注' : '取消关注',
						icon: 'success'
					});
				} catch (err) {
					console.error('关注操作失败', err);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
					// 回滚
					this.designer.is_follow = !newFollowState;
				}
			},

			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			sendMessage() {
				uni.navigateTo({
					url: `/pages/sub_base/chat/index?id=${this.designerId}`
				});
			},
			goToWorkDetail(id) {
				uni.navigateTo({
					url: `/pages/sub_base/creative-detail/index?id=${id}&workType=2`
				});
			},
			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/sub_base/creative-detail/index?id=${id}&workType=1`
				});
			},

			// 前端模拟点赞（实际应调用点赞接口）
			handleDesignLike(id) {
				const item = this.designWorks.find(w => w.id === id);
				if (item) {
					item.islike = !item.islike;
					item.likes += item.islike ? 1 : -1;
					if (item.likes < 0) item.likes = 0;
				}
			},
			handleRepresentaLike(id) {
				const item = this.representativeWorks.find(w => w.id === id);
				if (item) {
					item.islike = !item.islike;
					item.likes += item.islike ? 1 : -1;
					if (item.likes < 0) item.likes = 0;
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background-color: #f8f8f8;
		width: 100%;
	}

	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		z-index: 100;
	}

	.header-left {
		width: 88rpx;
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-icon {
		width: 48rpx;
		height: 48rpx;
	}

	.header-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333333;
	}

	.header-right {
		width: 88rpx;
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.content {
		background-color: #F2F8FC;
		height: calc(100vh - 0rpx);
	}

	.user-title {
		display: flex;
		align-items: center;
	}

	.designer-info-section {
		background-color: #ffffff;
		padding: 30rpx 30rpx;
		display: flex;
		flex-direction: column;
		margin-bottom: 16rpx;
	}

	.designer-avatar {
		width: 110rpx;
		height: 110rpx;
		border-radius: 60rpx;
		margin-right: 28rpx;
	}

	.designer-name-box {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.designer-name {
		font-size: 36rpx;
		font-weight: 600;
		color: #333333;
	}

	.designer-tag {
		font-size: 24rpx;
		color: #ffffff;
		background-color: #55aaff;
		padding: 4rpx 16rpx;
		border-radius: 24rpx;
	}

	.designer-description {
		font-size: 28rpx;
		color: #666666;
		margin: 40rpx 0;
	}

	.stats-section {
		display: flex;
		width: 100%;
		margin-bottom: 40rpx;
		justify-content: space-between;
		align-items: center;
	}

	.date-box {
		display: flex;
		justify-content: space-around;
		gap: 26rpx;
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
	}

	.stat-number {
		font-size: 34rpx;
		font-weight: 600;
		color: #333333;
	}

	.stat-label {
		font-size: 22rpx;
		color: #666666;
	}

	.action-buttons {
		display: flex;
		gap: 24rpx;
		justify-content: center;
		width: 100%;
	}

	.follow-btn,
	.message-btn {
		padding: 8rpx 40rpx;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
	}

	.follow-btn {
		background-color: #ff9966;
		color: #ffffff;
	}

	.message-btn {
		background-color: #ffffff;
		border: 2rpx solid #ff9966;
		color: #ff9966;
	}

	.tabs {
		display: flex;
		padding: 0 32rpx;
		justify-self: start;
		gap: 60rpx;
		height: 88rpx;
		align-items: flex-end;
	}

	.tab-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.tab-item.active .tab-text {
		color: #333333;
		font-weight: 600;
	}

	.tab-underline {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background-color: #333333;
	}

	.tab-text {
		font-size: 32rpx;
		color: #999999;
	}

	.tab-content {
		padding: 32rpx;
	}

	/* 	.works-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.work-item {
		width: calc(50% - 8rpx);
		overflow: hidden;
	} */

	.works-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		box-sizing: border-box;
	}

	.work-item {
		flex-basis: 48%;
		max-width: 48%;
		box-sizing: border-box;
		overflow: hidden;
	}

	.work-image {
		width: 100%;
		height: 480rpx;
	}

	.work-info {
		padding: 24rpx;
	}

	.work-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333333;
		display: block;
		margin-bottom: 16rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.work-meta {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.author-icon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 8rpx;
		border-radius: 50rpx;
	}

	.author-name {
		font-size: 24rpx;
		color: #666666;
	}

	.like-box {
		display: flex;
		align-items: center;
		gap: 8rpx;
		margin-left: auto;
	}

	.like-icon {
		width: 32rpx;
		height: 32rpx;
	}

	.like-count {
		font-size: 24rpx;
		color: #999999;
	}

	.empty-tip {
		text-align: center;
		color: #999;
		font-size: 28rpx;
		padding: 60rpx 0;
		width: 100%;
	}
	
	.identity-title {
		background-color: #E6F2F9;
		color: #84BDE3;
		padding: 2rpx 12rpx;
		border-radius: 12rpx;
		margin-left: 28rpx;
	}
	
	.mvp-img {
		height: 38rpx;
		/* width: 38rpx; */
		width: 138rpx;
		margin-left: 20rpx;
	}
	.designer-tag {
		display: flex;
		align-items: center;
		/* 保持原有样式 */
		font-size: 24rpx;
		padding: 0 14rpx 8rpx;
		/* 可根据需要调整 */
		margin-left: 24rpx;
		margin-top: 4rpx;
		border-radius: 30rpx;
		border: 2rpx solid #000;
		height: 44rpx;
	
		/* 新增：设置背景色和文字颜色，使其更清晰 */
		background-color: #fff;
		/* 或者透明 background-color: transparent; */
		color: #000;
	}
	
	.designer-icon {
		width: 22rpx;
		height: 22rpx;
		margin-right: 4rpx;
		/* 调整图标和文字之间的间距 */
		/* 如果需要垂直居中，可以加 margin-bottom: -2rpx; */
	}
</style>